package com.bsoft.gol.hbs.service.impl;

import com.alibaba.fastjson.JSON;
import com.bsoft.gol.hbs.dao.PcnBaseHpiDAO;
import com.bsoft.gol.hbs.dao.PcnHpiResidentDAO;
import com.bsoft.gol.hbs.dao.PcnHpiResidentLogDAO;
import com.bsoft.gol.hbs.dao.PcnHpiTypeDAO;
import com.bsoft.gol.hbs.utils.CommonUtils;
import com.google.common.base.Function;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.base.healthinfo.OdsHmDetail;
import hcn.base.healthinfo.OdsHmRecord;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.bean.hpi.*;
import pcn.service.hpi.AppPcnHpiService;
import pcn.vo.hpi.PcnHpiResidentItemDTO;
import pcn.vo.hpi.PcnHpiResidentItemVO;
import pcn.vo.hpi.PcnHpiTypeResidentDTO;
import pcn.vo.hpi.PcnHpiTypeResidentVO;
import service.rpc.BaseUserManageUnitIntf;
import service.rpc.OdsHmRecordService;

import java.util.*;
@SsdevService("appPcnHpiService")
public class AppPcnHpiServiceImpl implements AppPcnHpiService {
	private final  Logger logger = LoggerFactory.getLogger(AppPcnHpiServiceImpl.class);  
	@Autowired
	private PcnBaseHpiDAO pcnBaseHpiDAO;
	@Autowired
	private PcnHpiTypeDAO pcnHpiTypeDAO;
	@Autowired
	private PcnHpiResidentDAO pcnHpiResidentDAO;
	@Autowired
	private PcnHpiResidentLogDAO pcnHpiResidentLogDAO;
	@Autowired
	private OdsHmRecordService odsHmRecordService;
	@Autowired
	private BaseUserManageUnitIntf baseUserManageUnitIntf;
	/**
	 * 家医提交健康指标
	 * @return 
	 * @throws ControllerException 
	 */
	@RpcService
	@Override
	public void doctorPostPcnHpiResidents(PcnHpiResidentsDTO hpiResidentsDTO) throws ControllerException{
		/*PcnResponse<String> response = new PcnResponse<>();*/
		if(hpiResidentsDTO == null){
			throw new ControllerException("hpiResidentsDTO is null!");
		}
		if(hpiResidentsDTO.getMpiId() == null){
			throw new ControllerException("mpiId is null!");
		}
		boolean isEmpty = pcnHpiResidentDAO.findPcnHpiResidentsByMpiId(hpiResidentsDTO.getMpiId()).isEmpty();
		List<PcnHpiResident> pcnHpiResidents = hpiResidentsDTO.getList();
		for(PcnHpiResident pcnHpiResident:pcnHpiResidents){
			pcnHpiResident.setMpiId(hpiResidentsDTO.getMpiId());
			saveOrUpdatePcnHpiResident(pcnHpiResident,isEmpty);
		}
	}
	
	/**
	 * 是否是行状态过滤    true过滤，false不过滤
	 * @author  BsoftWang
	 * @created 2017年5月8日 下午7:28:02
	 * @param mpiId
	 * @return
	 * @return  boolean
	 */
	private boolean isFilter(String mpiId){
		if("-1".equals(mpiId.trim())){
			return false;
		}
		return true;
	}
	/**
	 * 后台获取所有的指标类别，及指标项,不区分状态的
	 * @author  BsoftWang
	 * @created 2017年5月9日 下午8:01:12
	 * @return
	 * @return  Collection<PcnHpiTypeResidentVO>
	 */
	public Collection<PcnHpiTypeResidentVO> getWebDefaultPcnHpiTypeResident(){
		List<PcnBaseHpi> pcnBaseHpiList = pcnBaseHpiDAO.findAll();
		Map<Integer,PcnHpiTypeResidentVO> pcnHpiResidentMap =  getDefaultPcnHpiTypeResidentMap(pcnBaseHpiList);
		List<PcnHpiType> pcnHpiTypes = pcnHpiTypeDAO.findPcnHpiTypes();
		PcnHpiTypeResidentVO hpiTypeResidentVO =  null;
		for(PcnHpiType el: pcnHpiTypes){
			hpiTypeResidentVO = pcnHpiResidentMap.get(el.getTypeId());
			if(hpiTypeResidentVO == null){
				hpiTypeResidentVO = new PcnHpiTypeResidentVO(new ArrayList<PcnHpiResidentItemVO>(0));
				setHpiTypeResidentVOHpiType(el.getTypeId(),hpiTypeResidentVO);
				pcnHpiResidentMap.put(el.getTypeId(), hpiTypeResidentVO);
			}
		}	
		return pcnHpiResidentMap.values();
	}
	/**
	 * 居民健康指标列表
	 * mpiId为－1时，取默认的健康指标，并且不进行是否启用状态判断
	 * @return 
	 * @throws ControllerException 
	 */
	@RpcService
	@Override
	public Collection<PcnHpiTypeResidentDTO>  residentHpiList(String mpiId) throws ControllerException{
		if(StringUtils.isBlank(mpiId)){
			throw new ControllerException("mpiId is null!");
		}
		Collection<PcnHpiTypeResidentDTO> collection =  new ArrayList<>();
		List<OdsHmRecord> odsHmRecordsByMpiId = odsHmRecordService.findOdsHmRecordsByMpiId(mpiId);
		if (CommonUtils.isNotEmpty(odsHmRecordsByMpiId)){
			for (OdsHmRecord odsHmRecord : odsHmRecordsByMpiId) {
				List<PcnHpiResidentItemDTO> itemList = new ArrayList<>();
				PcnHpiTypeResidentDTO pcnHpiTypeResidentDTO = new PcnHpiTypeResidentDTO();
				String hmRecordId = odsHmRecord.getHmRecordId();
				pcnHpiTypeResidentDTO.setStatus(odsHmRecord.getSource());
				//检测项目的名称编码代码
				pcnHpiTypeResidentDTO.setTypeCode(odsHmRecord.getItemCode());
				pcnHpiTypeResidentDTO.setTypeId(odsHmRecord.getHmRecordId());
				pcnHpiTypeResidentDTO.setTypeName(odsHmRecord.getItemName());
				List<OdsHmDetail> odsHmDetailsByHmRecordId = odsHmRecordService.findOdsHmDetailsByHmRecordId(hmRecordId);
				if (CommonUtils.isNotEmpty(odsHmDetailsByHmRecordId)){
					for (OdsHmDetail odsHmDetail : odsHmDetailsByHmRecordId) {
						PcnHpiResidentItemDTO itemDTO = new PcnHpiResidentItemDTO();
						itemDTO.setHpiCode(odsHmDetail.getHpiCode());
						itemDTO.setHpiId(odsHmDetail.getHmDetailId());
						itemDTO.setHpiName(odsHmDetail.getHpiName());
						itemDTO.setHpiUnit(odsHmDetail.getHpiUnit());
						itemDTO.setLowerLimit(odsHmDetail.getLowerLimit());
						itemDTO.setUpperLimit(odsHmDetail.getUpperLimit());
						itemDTO.setStatus(odsHmDetail.getResultStatus());
						itemList.add(itemDTO);
					}
					pcnHpiTypeResidentDTO.setItemList(itemList);
				}
				collection.add(pcnHpiTypeResidentDTO);
			}
		}
		return collection;
	}
	
	public void syncReResident(String mpiId){
		List<PcnBaseHpi> baseHpis = 	pcnBaseHpiDAO.findWaitSyncPcnBasehpiByMpiId(mpiId);
		PcnHpiResident pcnHpiResident = null;
		if(!baseHpis.isEmpty()){
			for(PcnBaseHpi el : baseHpis){
				 pcnHpiResident = new PcnHpiResident();
				 pcnHpiResident.setHpiCode(el.getHpiCode());
				 pcnHpiResident.setHpiId(el.getHpiId());
				 pcnHpiResident.setLowerLimit(el.getLowerLimit());
				 pcnHpiResident.setUpperLimit(el.getUpperLimit());
				 pcnHpiResident.setTypeId(el.getTypeId());
				 pcnHpiResident.setMpiId(mpiId);
				 try {
					saveOrUpdatePcnHpiResident(pcnHpiResident, true);
					logger.info("sysnc HpiId "+ pcnHpiResident.getHpiId() + "success!");
				} catch (ControllerException e) {
					logger.info("ignore",e);
				}
			}
		}
	}
	
	/**
	 * 居民健康指标列表不带类型的
	 * @return 
	 * @throws ControllerException 
	 */
	@RpcService
	@Override
	public List<PcnHpiResidentItemVO>  residentHpiListWithNoType(String mpiId) throws ControllerException{
		if(StringUtils.isBlank(mpiId)){
			  throw new ControllerException("mpiId is null!");
		}
		List<PcnHpiResident> pcnHpiResidentList = pcnHpiResidentDAO.findPcnHpiResidentsByMpiIdAndStatus(mpiId);
		List<PcnHpiResidentItemVO> bodylist = new ArrayList<>();
		if(pcnHpiResidentList.isEmpty()){
			List<PcnBaseHpi> pcnBaseHpis= pcnBaseHpiDAO.findAllByStatus();
			for(PcnBaseHpi baseHpi : pcnBaseHpis){
				PcnHpiResidentItemVO itemVO = toHpiTypeResidentVO(baseHpi);
			//	if(ViewBean.view(itemVO.getIsable())){
					bodylist.add(itemVO);
			//	}
			}
		}else{
			syncReResident(mpiId);
			for(PcnHpiResident hpiResident:pcnHpiResidentList){
				PcnHpiResidentItemVO itemVO = toHpiTypeResidentVO(hpiResident);
				//if(ViewBean.view(itemVO.getIsable())){
					bodylist.add(itemVO);
				//}
			}
		}
		return bodylist;
	}

    /**
     * 获取居民健康指标项Map
     * @param mpiId
     * @return
     */
	public Map<String, PcnHpiResidentItemVO> getHpiResidentMap(String mpiId){
		List<PcnHpiResidentItemVO> hpiResidentItemList = null;
		try {
			hpiResidentItemList = residentHpiListWithNoType(mpiId);
		} catch (ControllerException e) {
            logger.error("查询居民健康指标列表异常", e);
		}
		Map<String, PcnHpiResidentItemVO> hpiResidentMap = com.google.common.collect.Maps.uniqueIndex(hpiResidentItemList, new Function<PcnHpiResidentItemVO, String>() {
			@Override
			public String apply(PcnHpiResidentItemVO input) {
				return input.getHpiCode();
			}
		});
		
		return hpiResidentMap;
	}

	
	private Map<Integer,PcnHpiTypeResidentVO> getDefaultPcnHpiTypeResidentMap(List<PcnBaseHpi> pcnBaseHpiList){
		Map<Integer,PcnHpiTypeResidentVO> pcnHpiResidentMap = new HashMap<>();
		PcnHpiTypeResidentVO hpiTypeResidentVO =  null;
		for(PcnBaseHpi el: pcnBaseHpiList){
			hpiTypeResidentVO = pcnHpiResidentMap.get(el.getTypeId());
			if(hpiTypeResidentVO == null){
				hpiTypeResidentVO = new PcnHpiTypeResidentVO(new ArrayList<PcnHpiResidentItemVO>());
				//设置指标类别
				setHpiTypeResidentVOHpiType(el.getTypeId(),hpiTypeResidentVO);
				//if(ViewBean.view(isFilter,able)){
						pcnHpiResidentMap.put(el.getTypeId(), hpiTypeResidentVO);
				/*}else{
					continue;
				}*/
			}
			PcnHpiResidentItemVO itemVO = toHpiTypeResidentVO(el);
			//if(ViewBean.view(isFilter, itemVO.getIsable())){
				hpiTypeResidentVO.getItemList().add(itemVO);
			//}
		}	
		return pcnHpiResidentMap;
	}
	/**
	 * 获取默认的健康指标
	 */
	private Collection<PcnHpiTypeResidentVO> getDefaultPcnHpiTypeResident(List<PcnBaseHpi> pcnBaseHpiList){
		return getDefaultPcnHpiTypeResidentMap(pcnBaseHpiList).values();
	}
	/**
	 * 获取经过医生修改后的居民健康指标
	 * @param pcnHpiResidentList
	 * @return
	 */
	private Collection<PcnHpiTypeResidentVO> getPcnHpiTypeResident(List<PcnHpiResident> pcnHpiResidentList){
		Map<Integer,PcnHpiTypeResidentVO> pcnHpiResidentMap = new HashMap<>();
		PcnHpiTypeResidentVO hpiTypeResidentVO =  null;
		for(PcnHpiResident el: pcnHpiResidentList){
			hpiTypeResidentVO = pcnHpiResidentMap.get(el.getTypeId());
			if(hpiTypeResidentVO == null){
				hpiTypeResidentVO = new PcnHpiTypeResidentVO(new ArrayList<PcnHpiResidentItemVO>());
				//设置指标类别
				//boolean  able = 
				setHpiTypeResidentVOHpiType(el.getTypeId(),hpiTypeResidentVO);	
			//	if(ViewBean.view(able)){
					pcnHpiResidentMap.put(el.getTypeId(), hpiTypeResidentVO);
				//}else{
				///	continue;
				//}
			}
			PcnHpiResidentItemVO itemVO =  toHpiTypeResidentVO(el);
			//if(ViewBean.view(itemVO.getIsable())){
				//转化成页面所需要的健康指标数据
				hpiTypeResidentVO.getItemList().add(itemVO);
			//}
		}
		return 	pcnHpiResidentMap.values();
	}
	
	/**
	 * 把默认健康指标转化成PcnHpiTypeResidentVO
	 * @param el
	 */
	private PcnHpiResidentItemVO toHpiTypeResidentVO(PcnBaseHpi el){
		PcnHpiResidentItemVO hpiResidentItemVO = new PcnHpiResidentItemVO();
		BeanUtils.copyProperties(el, hpiResidentItemVO);
		//hpiResidentItemVO.setIsable(ViewStatus.enable.getValue().equals(el.getStatus()));
		return hpiResidentItemVO;
	}
	
	/**
	 * 把居民的健康指标转化成PcnHpiTypeResidentVO
	 * @param el
	 */
	private PcnHpiResidentItemVO toHpiTypeResidentVO(PcnHpiResident el){
		PcnHpiResidentItemVO hpiResidentItemVO = new PcnHpiResidentItemVO();
		BeanUtils.copyProperties(el, hpiResidentItemVO);
		PcnBaseHpi pcnBaseHpi = pcnBaseHpiDAO.findPcnBasehpiById(el.getHpiId());
		//hpiResidentItemVO.setIsable(ViewStatus.enable.getValue().equals(pcnBaseHpi.getStatus()));
		
		if(pcnBaseHpi != null){
		
			hpiResidentItemVO.setHpiName(pcnBaseHpi.getHpiName());
			hpiResidentItemVO.setHpiUnit(pcnBaseHpi.getHpiUnit());
		}
		
		
		return hpiResidentItemVO;
	}
	
	/**
	 * 设置指标类别
	 * @param typeId
	 * @param hpiTypeResidentVO
	 * 返回是否启用
	 */
	private void setHpiTypeResidentVOHpiType(Integer typeId,PcnHpiTypeResidentVO hpiTypeResidentVO){
		PcnHpiType pcnHpiType =	pcnHpiTypeDAO.getPcnHpiTypeById(typeId);
		hpiTypeResidentVO.setTypeCode(pcnHpiType.getTypeCode());
		hpiTypeResidentVO.setTypeName(pcnHpiType.getTypeName());
		hpiTypeResidentVO.setTypeId(pcnHpiType.getTypeId());
		hpiTypeResidentVO.setStatus(pcnHpiType.getStatus());
		//return ViewStatus.enable.getValue().equals(pcnHpiType.getStatus());
	}
	
	
	/**
	 * 保存或者修改居民健康指标
	 * @param pcnHpiResident
	 * @param isSave
	 * @throws ControllerException 
	 */
	private void saveOrUpdatePcnHpiResident(PcnHpiResident pcnHpiResident, boolean isSave) throws ControllerException{
		if(StringUtils.isBlank(pcnHpiResident.getHpiCode())){
			throw new ControllerException("HpiCode not be null!");
		}
		
		List<PcnBaseHpi> baseHpiList = pcnBaseHpiDAO.findPcnBasehpiByHpiCode(pcnHpiResident.getHpiCode());
		if(baseHpiList.isEmpty()){
			throw new ControllerException("HpiCode not exists!");
		}
		PcnBaseHpi baseHpi = baseHpiList.get(0);
		pcnHpiResident.setTypeId(baseHpi.getTypeId());
		pcnHpiResident.setHpiId(baseHpi.getHpiId());
		if(isSave){
			pcnHpiResident.setTenantId(baseUserManageUnitIntf.getUserIdByOnline().getTenantId());
			pcnHpiResident.setCreateUser(baseUserManageUnitIntf.getUserIdByOnline().getUserId());
			pcnHpiResident.setCreateDt(new Date());
			//保存
			pcnHpiResidentDAO.save(pcnHpiResident);
		}else{
			pcnHpiResident.setLastModifyUser(baseUserManageUnitIntf.getUserIdByOnline().getUserId());
			pcnHpiResident.setLastModifyDt(new Date());
			List<PcnHpiResident> temList = pcnHpiResidentDAO.findPcnHpiResidentsByMpiIdAndHpiId(pcnHpiResident.getMpiId(), pcnHpiResident.getHpiId());
			if(temList.isEmpty()){
				logger.warn(JSON.toJSONString(pcnHpiResident)+" has been deleted!");
				throw new ControllerException("pcnHpiResident not exists! pcnHpiResident detail:"+JSON.toJSONString(pcnHpiResident));
			}
			//更新
			pcnHpiResidentDAO.updatePcnHpiResident(pcnHpiResident);
			pcnHpiResident = temList.get(0);
		}
		//写入日志
		pcnHpiResidentLogDAO.save(toPcnHpiResidentLog(pcnHpiResident));
	}
	
	private PcnHpiResidentLog toPcnHpiResidentLog(PcnHpiResident pcnHpiResident){
		PcnHpiResidentLog hpiResidentLog = new PcnHpiResidentLog();
		BeanUtils.copyProperties(pcnHpiResident, hpiResidentLog, new String[]{"logId"});
		return hpiResidentLog;
	}
	
	public AppPcnHpiServiceImpl() {
		super();
	}
}
